<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="shell,子网掩码,网络," />





  <link rel="alternate" href="/atom.xml" title="大牙的杂货铺" type="application/atom+xml" />






<meta name="description" content="利用规律进行口算netmask转CIDR例如：255.255.192.0  255.0.0.0、255.255.0.0、255.255.255.0、255.255.255.255 以上四种一看便知分别是8、16、24、32   例子中去掉所有255.的字符和.及其后面的字符，得到了192 用256减去192，得到了64">
<meta name="keywords" content="shell,子网掩码,网络">
<meta property="og:type" content="article">
<meta property="og:title" content="shell实现netmask掩码和cidr掩码位转换">
<meta property="og:url" content="http://linuxgeeks.github.io/2017/12/26/2017-12-26-134510-shell实现netmask掩码和cidr掩码位转换/index.html">
<meta property="og:site_name" content="大牙的杂货铺">
<meta property="og:description" content="利用规律进行口算netmask转CIDR例如：255.255.192.0  255.0.0.0、255.255.0.0、255.255.255.0、255.255.255.255 以上四种一看便知分别是8、16、24、32   例子中去掉所有255.的字符和.及其后面的字符，得到了192 用256减去192，得到了64，也就是2的6次方 XXX.XXX.192.XXX  24-6=18 192在第">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-30T14:14:04.950Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="shell实现netmask掩码和cidr掩码位转换">
<meta name="twitter:description" content="利用规律进行口算netmask转CIDR例如：255.255.192.0  255.0.0.0、255.255.0.0、255.255.255.0、255.255.255.255 以上四种一看便知分别是8、16、24、32   例子中去掉所有255.的字符和.及其后面的字符，得到了192 用256减去192，得到了64，也就是2的6次方 XXX.XXX.192.XXX  24-6=18 192在第">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://linuxgeeks.github.io/2017/12/26/2017-12-26-134510-shell实现netmask掩码和cidr掩码位转换/"/>





  <title>shell实现netmask掩码和cidr掩码位转换 | 大牙的杂货铺</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/mengdaya"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大牙的杂货铺</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://linuxgeeks.github.io/2017/12/26/2017-12-26-134510-shell实现netmask掩码和cidr掩码位转换/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="孟庆宇">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大牙的杂货铺">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">shell实现netmask掩码和cidr掩码位转换</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-26T13:45:10+08:00">
                2017-12-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/shell拓展/" itemprop="url" rel="index">
                    <span itemprop="name">shell拓展</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2,244
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="利用规律进行口算"><a href="#利用规律进行口算" class="headerlink" title="利用规律进行口算"></a>利用规律进行口算</h1><h2 id="netmask转CIDR"><a href="#netmask转CIDR" class="headerlink" title="netmask转CIDR"></a>netmask转CIDR</h2><p>例如：255.255.192.0</p>
<ul>
<li>255.0.0.0、255.255.0.0、255.255.255.0、255.255.255.255<ul>
<li>以上四种一看便知分别是8、16、24、32</li>
</ul>
</li>
<li>例子中去掉所有<code>255.</code>的字符和<code>.</code>及其后面的字符，得到了192</li>
<li>用256减去192，得到了64，也就是2的6次方</li>
<li><code>XXX.XXX.192.XXX</code>  24-6=18<ul>
<li>192在第一段，用8减</li>
<li>192在第二段，用16减</li>
<li>192在第三段，用24减</li>
<li>192在第四段，用32减</li>
</ul>
</li>
</ul>
<h2 id="CIDR转netmask"><a href="#CIDR转netmask" class="headerlink" title="CIDR转netmask"></a>CIDR转netmask</h2><p>例如：20==&gt;255.255.240.0</p>
<ul>
<li>根据上面的进行反推</li>
<li>8、16、24、32可直接转换</li>
<li>24-20=4<ul>
<li>小于8则用8减 </li>
<li>大于8小于16则用16减</li>
<li>大于16小于24则用24减</li>
<li>大于24小于32则用32减</li>
</ul>
</li>
<li>求得2的N次幂，即：2的4次方得到16，256-16=240</li>
<li><code>255.255.XXX.0</code>，这里的XXX是240<ul>
<li>小于8则是<code>XXX.0.0.0</code></li>
<li>大于8小于16则<code>255.XXX.0.0</code></li>
<li>大于16小于24则<code>255.255.XXX.0</code></li>
<li>大于24小于32则<code>255.255.255.XXX</code></li>
</ul>
</li>
</ul>
<h1 id="使用自带命令ipcalc"><a href="#使用自带命令ipcalc" class="headerlink" title="使用自带命令ipcalc"></a>使用自带命令ipcalc</h1><ul>
<li>常用选项</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">-b, --broadcast     Display calculated broadcast address</span><br><span class="line">-h, --hostname      Show hostname determined via DNS</span><br><span class="line">-m, --netmask       Display default netmask <span class="keyword">for</span> IP (class A, B, or C)</span><br><span class="line">-n, --network       Display network address</span><br><span class="line">-p, --prefix        Display network prefix</span><br></pre></td></tr></table></figure>
<ul>
<li>使用示例</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$ ipcalc -pmnb 222.58.15.18/29</span><br><span class="line"></span><br><span class="line">NETMASK=255.255.255.248</span><br><span class="line">PREFIX=29</span><br><span class="line">BROADCAST=222.58.15.23</span><br><span class="line">NETWORK=222.58.15.16</span><br></pre></td></tr></table></figure>
<h1 id="perl开发的ipcalc"><a href="#perl开发的ipcalc" class="headerlink" title="perl开发的ipcalc"></a>perl开发的ipcalc</h1><ul>
<li>官网：<a href="http://jodies.de/ipcalc" target="_blank" rel="noopener">http://jodies.de/ipcalc</a></li>
<li>示例</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">$ ipcalc 192.168.0.1/24 </span><br><span class="line"></span><br><span class="line">Address:   192.168.0.1          11000000.10101000.00000000. 00000001</span><br><span class="line">Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000</span><br><span class="line">Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111</span><br><span class="line">=&gt;</span><br><span class="line">Network:   192.168.0.0/24       11000000.10101000.00000000. 00000000</span><br><span class="line">HostMin:   192.168.0.1          11000000.10101000.00000000. 00000001</span><br><span class="line">HostMax:   192.168.0.254        11000000.10101000.00000000. 11111110</span><br><span class="line">Broadcast: 192.168.0.255        11000000.10101000.00000000. 11111111</span><br><span class="line">Hosts/Net: 254                   Class C, Private Internet</span><br></pre></td></tr></table></figure>
<h1 id="来自openwrt的shell脚本"><a href="#来自openwrt的shell脚本" class="headerlink" title="来自openwrt的shell脚本"></a>来自openwrt的shell脚本</h1><ul>
<li>内容来源于：<a href="https://forum.openwrt.org/viewtopic.php?pid=220781#p220781" target="_blank" rel="noopener">openwrt</a></li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#!/bin/bash</span></span><br><span class="line"></span><br><span class="line">mask2cdr ()</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment"># Assumes there's no "255." after a non-255 byte in the mask</span></span><br><span class="line">   <span class="built_in">local</span> x=<span class="variable">$&#123;1##*255.&#125;</span></span><br><span class="line">   <span class="built_in">set</span> -- 0^^^128^192^224^240^248^252^254^ $(( (<span class="variable">$&#123;#1&#125;</span> - <span class="variable">$&#123;#x&#125;</span>)*2 )) <span class="variable">$&#123;x%%.*&#125;</span></span><br><span class="line">   x=<span class="variable">$&#123;1%%$3*&#125;</span></span><br><span class="line">   <span class="built_in">echo</span> $(( <span class="variable">$2</span> + (<span class="variable">$&#123;#x&#125;</span>/4) ))</span><br><span class="line">&#125;</span><br><span class="line">cdr2mask ()</span><br><span class="line">&#123;</span><br><span class="line">   <span class="comment"># Number of args to shift, 255..255, first non-255 byte, zeroes</span></span><br><span class="line">   <span class="built_in">set</span> -- $(( 5 - (<span class="variable">$1</span> / 8) )) 255 255 255 255 $(( (255 &lt;&lt; (8 - (<span class="variable">$1</span> % 8))) &amp; 255 )) 0 0 0</span><br><span class="line">   [ <span class="variable">$1</span> -gt 1 ] &amp;&amp; <span class="built_in">shift</span> <span class="variable">$1</span> || <span class="built_in">shift</span></span><br><span class="line">   <span class="built_in">echo</span> <span class="variable">$&#123;1-0&#125;</span>.<span class="variable">$&#123;2-0&#125;</span>.<span class="variable">$&#123;3-0&#125;</span>.<span class="variable">$&#123;4-0&#125;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment"># examples:</span></span><br><span class="line">mask2cdr 255.255.255.0</span><br><span class="line">cdr2mask 24</span><br></pre></td></tr></table></figure>
<h2 id="思路说明"><a href="#思路说明" class="headerlink" title="思路说明"></a>思路说明</h2><h3 id="mask2cdr"><a href="#mask2cdr" class="headerlink" title="mask2cdr()"></a>mask2cdr()</h3><ul>
<li>To get the CIDR prefix from a dot-decimal netmask like this one:<br>要从像下面这样的点分十进制掩码获得CIDR子网掩码</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">255.255.192.0</span><br></pre></td></tr></table></figure>
<ul>
<li>you first have to convert the four octets to binary and then count the most significant bits (i.e. the number of leading ones):<br>首先你必须转换成四个八位二进制，而且算出占了1的位数</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">11111111.11111111.11000000.00000000 <span class="comment"># 18 ones = /18 in CIDR</span></span><br></pre></td></tr></table></figure>
<ul>
<li>This function does that rather creatively. First, we strip off all of the leading 255 octets (i.e. the octets that are all ones in binary) and store the results in variable x:<br>这个函数确实极具创造性。首先，我们将传入函数的的第一个位置参数（即点分十进制子网掩码）去掉所有开头的255，然后复制给变量x</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">local</span> x=<span class="variable">$&#123;1##*255.&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p> This step uses parameter expansion, which the entire script relies on pretty heavily. If we continue with our example netmask of 255.255.192.0, we now have the following values:<br>这一步我们使用参数扩展，整个脚本对此有很强的依赖性。如果我们根据刚刚的例子继续看，会得到如下值</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$1</span>: 255.255.192.0 </span><br><span class="line"><span class="variable">$x</span>: 192.0</span><br></pre></td></tr></table></figure>
<ul>
<li>Next we set three variables: $1, $2, and $3. These are called positional parameters; they are much like ordinary named variables but are typically set when you pass arguments to a script or function. We can set the values directly using set –, for example:<br>接下来我们设置了三个变量：$1，$2和$3，他们都是位置参数，和普通变量大同小异，但是当你将参数传给一个脚本或者函数时他们是很典型的设置。我们可以直接使用<code>set --</code>来设定变量的值，列如：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">set</span> -- foo bar <span class="comment"># $1 = foo, $2 = bar</span></span><br></pre></td></tr></table></figure>
<ul>
<li>I prefer using named variables over positional parameters since it makes scripts easier to read and debug, but the end result is the same. We set $1 to:<br>相比较位置参数，我更喜欢使用定义好的变量，因为这样使得脚本更容易阅读和调试bug，但是最终的结果都是相同的，我们把位置参数$1设置为：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0^^^128^192^224^240^248^252^254^</span><br></pre></td></tr></table></figure>
<blockquote>
<p>This is really just a table to convert certain decimal values to binary and count the number of 1 bits. We’ll come back to this later.<br>这其实只是一个用来转换十进制到二进制，统计1bits数量的一个表。我们稍后将会回顾这里</p>
</blockquote>
<ul>
<li>We set $2 to<br>我们将位置参数$2设置为：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(( (<span class="variable">$&#123;#1&#125;</span> - <span class="variable">$&#123;#x&#125;</span>)*2 ))</span><br></pre></td></tr></table></figure>
<blockquote>
<p>This looks complex, but it is really just counting the number of 1 bits we stripped off in the first command. It breaks down to this:<br>这个看起来有些复杂，但是其实只是计算我们从第一个命令中去掉（二进制数中八个位都占了1的位）的数量。它划分成了这样：</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">(number of chars <span class="keyword">in</span> <span class="variable">$1</span> - number of chars <span class="keyword">in</span> <span class="variable">$x</span>) * 2</span><br><span class="line"><span class="comment"># 如果传递给函数的子网掩码是255.255.255.192的话，那么其实就是（15-3）*2=24</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>which in our case works out to<br>在我们的情况下，其实就是这样：</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(13 - 5) * 2 = 16</span><br></pre></td></tr></table></figure>
<blockquote>
<p>We stripped off two octets so we get 16. Makes sense.<br>我们去除了两个（在二进制都占了1的位数=8）8位因此得到了16</p>
</blockquote>
<ul>
<li>We set $3 to:<br>我们将位置参数$3设置为：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$&#123;x%%.*&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>which is the value of $x with everything after the first . stripped off. In our case, this is 192.<br>从刚开始到现在$x的值，在我们的情况下已经赋值为192</p>
</blockquote>
<ul>
<li>We need to convert this number to binary and count the number of 1 bits in it, so let’s go back to our “conversion table.” We can divide the table into equal chunks of four characters each:<br>我们需要将这个数字转换为二进制并计算占了1的位的数量，让我们回到我们的“转换表”。我们可以把表分成每个块的字符数等于四的块：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0^^^ 128^ 192^ 224^ 240^ 248^ 252^ 254^</span><br></pre></td></tr></table></figure>
<blockquote>
<p>In binary, the above numbers are:<br>转换为二进制就是</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">00000000 10000000 11000000 11100000 11110000 11111000 11111100 11111110</span><br><span class="line"><span class="comment"># 0 ones 1 one    2 ones   3 ones   ...</span></span><br></pre></td></tr></table></figure>
<ul>
<li>If we count from the left, each four-character block in the table corresponds to an additional 1 bit in binary. We’re trying to convert 192, so let’s first lop off the rightmost part of the table, from 192 on, and store it in x:<br>如果我们从左边数，表中的每个四字符的块对应一个额外 占了1的位 的二进制数。我们正试图转换 192 ，所以让我们先剔除掉从192开头的了最右边的表，并赋值给x ：</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x=<span class="variable">$&#123;1%%$3*&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>The value of $x is now<br>$x的值现在就是</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">0^^^128^</span><br></pre></td></tr></table></figure>
<blockquote>
<p>which contains two four-character blocks, or two 1 bits in binary.<br>包含了两个4字符的块或者说是两个占了1位的二进制</p>
</blockquote>
<ul>
<li>Now we just need to add up the 1 bits from our leading 255 octets (16 total, stored in variable $2) and the 1 bits from the previous step (2 total):<br>现在我们只需要把之前算的两个（二进制下都为1的）八位组，（16个，赋值给位变量 $ 2 ），加上从第二步的表中算出$x在二进制中占了1的位的数2</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> $(( <span class="variable">$2</span> + (<span class="variable">$&#123;#x&#125;</span>/4) ))</span><br></pre></td></tr></table></figure>
<p>where<br>其中</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$&#123;#x&#125;</span>/4</span><br></pre></td></tr></table></figure>
<ul>
<li>is the number of characters in $x divided by four, i.e. the number of four-character blocks in $x.<br>是$x的字符数除以四（每四个字符是一个块）</li>
</ul>
<p>Output:<br>输出结果</p>
<p>18</p>
<h3 id="cdr2mask"><a href="#cdr2mask" class="headerlink" title="cdr2mask()"></a>cdr2mask()</h3><p>Let’s keep running with our previous example, which had a CIDR prefix of 18.</p>
<p>We use set – to set positional parameters $1 through $9:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$1</span>: $(( 5 - (<span class="variable">$1</span> / 8) ))  <span class="comment"># 5 - (18 / 8) = 3 [integer math]</span></span><br><span class="line"><span class="variable">$2</span>: 255</span><br><span class="line"><span class="variable">$3</span>: 255</span><br><span class="line"><span class="variable">$4</span>: 255</span><br><span class="line"><span class="variable">$5</span>: 255</span><br><span class="line"><span class="variable">$6</span>: $(( (255 &lt;&lt; (8 - (<span class="variable">$1</span> % 8))) &amp; 255 ))  <span class="comment"># (255 &lt;&lt; (8 - (18 % 8))) &amp; 255 = 192</span></span><br><span class="line"><span class="variable">$7</span>: 0</span><br><span class="line"><span class="variable">$8</span>: 0</span><br><span class="line"><span class="variable">$9</span>: 0</span><br></pre></td></tr></table></figure>
<p>Let’s examine the formulas used to set $1 and $6 a little closer. $1 is set to:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(( 5 - (<span class="variable">$1</span> / 8) ))</span><br></pre></td></tr></table></figure>
<p>The maximum and minimum possible values for a CIDR prefix are 32 for netmask</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">11111111.11111111.11111111.11111111</span><br></pre></td></tr></table></figure>
<p>and 0 for netmask</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">00000000.00000000.00000000.00000000</span><br></pre></td></tr></table></figure>
<p>The above formula uses integer division, so the possible results range from 1 to 5:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">5 - (32 / 8) = 1</span><br><span class="line">5 - ( 0 / 8) = 5</span><br></pre></td></tr></table></figure>
<p>$6 is set to:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">$(( (255 &lt;&lt; (8 - (<span class="variable">$1</span> % 8))) &amp; 255 ))</span><br></pre></td></tr></table></figure>
<p>Let’s break this down for our example CIDR prefix of 18. First we take the modulus and do some subtraction:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">8 - (18 % 8) = 6</span><br></pre></td></tr></table></figure>
<p>Next we bitwise shift 255 by this value:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">255 &lt;&lt; 6</span><br></pre></td></tr></table></figure>
<p>This is the same as pushing six 0 bits onto the end of 255 in binary:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">11111111000000</span><br></pre></td></tr></table></figure>
<p>Finally, we bitwise AND this value with 255:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">11111111000000 &amp;</span><br><span class="line">00000011111111  <span class="comment"># 255</span></span><br></pre></td></tr></table></figure>
<p>which gives</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">00000011000000</span><br></pre></td></tr></table></figure>
<p>or simply</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">11000000</span><br></pre></td></tr></table></figure>
<p>Look familiar? This is the third octet in our netmask in binary:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">11111111.11111111.11000000.00000000</span><br><span class="line">                  ^------^</span><br></pre></td></tr></table></figure>
<p>In decimal, the value is 192.</p>
<p>Next we shift the positional parameters based on the value of $1:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[ <span class="variable">$1</span> -gt 1 ] &amp;&amp; <span class="built_in">shift</span> <span class="variable">$1</span> || <span class="built_in">shift</span></span><br></pre></td></tr></table></figure>
<p>In our case, the value of $1 is 3, so we shift the positional parameters 3 to the left. The previous value of $4 becomes the new value of $1, the previous value of $5 becomes the value of $2, and so on:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">$1</span>: 255</span><br><span class="line"><span class="variable">$2</span>: 255</span><br><span class="line"><span class="variable">$3</span>: 192</span><br><span class="line"><span class="variable">$4</span>: 0</span><br><span class="line"><span class="variable">$5</span>: 0</span><br><span class="line"><span class="variable">$6</span>: 0</span><br></pre></td></tr></table></figure>
<p>These values should look familiar: they are the decimal octets from our netmask (with a couple of extra zeros tacked on at the end). To get the netmask, we simply print out the first four with dots in between them:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">echo</span> <span class="variable">$&#123;1-0&#125;</span>.<span class="variable">$&#123;2-0&#125;</span>.<span class="variable">$&#123;3-0&#125;</span>.<span class="variable">$&#123;4-0&#125;</span></span><br></pre></td></tr></table></figure>
<p>The -0 after each parameter says to use 0 as the default value if the parameter is not set.</p>
<p>Output:</p>
<p>255.255.192.0</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>有钱任性，请我吃包辣条</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="孟庆宇 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="孟庆宇 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    孟庆宇
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://linuxgeeks.github.io/2017/12/26/2017-12-26-134510-shell实现netmask掩码和cidr掩码位转换/" title="shell实现netmask掩码和cidr掩码位转换">http://linuxgeeks.github.io/2017/12/26/2017-12-26-134510-shell实现netmask掩码和cidr掩码位转换/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/shell/" rel="tag"><i class="fa fa-tag"></i> shell</a>
          
            <a href="/tags/子网掩码/" rel="tag"><i class="fa fa-tag"></i> 子网掩码</a>
          
            <a href="/tags/网络/" rel="tag"><i class="fa fa-tag"></i> 网络</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/12/25/2017-12-25-121210-使用dig命令写一个定时解析脚本/" rel="next" title="使用dig命令写一个定时解析脚本">
                <i class="fa fa-chevron-left"></i> 使用dig命令写一个定时解析脚本
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/12/27/2017-12-27-082310-vim中一键添加版权信息及常用配置/" rel="prev" title="vim中一键添加版权信息及常用配置">
                vim中一键添加版权信息及常用配置 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="孟庆宇" />
            
              <p class="site-author-name" itemprop="name">孟庆宇</p>
              <p class="site-description motion-element" itemprop="description">书山有路勤为径，学海无涯苦作舟</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">109</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">56</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/mengdaya" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yourname@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-globe"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ibm.com/developerworks/cn/" title="IBM developerWorks" target="_blank">IBM developerWorks</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://iissnan.com/progit/" title="Pro Git" target="_blank">Pro Git</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.freeoa.net/index/" title="freeOA" target="_blank">freeOA</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ttlsa.com/" title="运维生存时间" target="_blank">运维生存时间</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.361way.com/" title="运维之路" target="_blank">运维之路</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.yiibai.com/" title="易百教程" target="_blank">易百教程</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.centoscn.com/" title="CentOS中文站" target="_blank">CentOS中文站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.linuxprobe.com/" title="Linux就该这么学" target="_blank">Linux就该这么学</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.netingcn.com/" title="网络进行时" target="_blank">网络进行时</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ruanyifeng.com/blog/" title="阮一峰的网络日志" target="_blank">阮一峰的网络日志</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com" title="廖雪峰的官方网站" target="_blank">廖雪峰的官方网站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yihui.name/cn/" title="谢益辉的博客" target="_blank">谢益辉的博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://coolshell.cn" title="酷壳" target="_blank">酷壳</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#利用规律进行口算"><span class="nav-number">1.</span> <span class="nav-text">利用规律进行口算</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#netmask转CIDR"><span class="nav-number">1.1.</span> <span class="nav-text">netmask转CIDR</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CIDR转netmask"><span class="nav-number">1.2.</span> <span class="nav-text">CIDR转netmask</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#使用自带命令ipcalc"><span class="nav-number">2.</span> <span class="nav-text">使用自带命令ipcalc</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#perl开发的ipcalc"><span class="nav-number">3.</span> <span class="nav-text">perl开发的ipcalc</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#来自openwrt的shell脚本"><span class="nav-number">4.</span> <span class="nav-text">来自openwrt的shell脚本</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#思路说明"><span class="nav-number">4.1.</span> <span class="nav-text">思路说明</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#mask2cdr"><span class="nav-number">4.1.1.</span> <span class="nav-text">mask2cdr()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#cdr2mask"><span class="nav-number">4.1.2.</span> <span class="nav-text">cdr2mask()</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文章总结于网络，转载请注明出处</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="true"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
</html>
